﻿using Shop.Collect;
using Shop.ExtendService;
using Shop.LocalEvent;
using Shop.Model.DB;
using Shop.RemoteModel.PageModule.Model;
using Shop.RemoteModel.PageModule.ModuleConfig;
using Shop.Service.Helper;
using Shop.Service.Interface;
using WeDonekRpc.Client;
using WeDonekRpc.Helper;

namespace Shop.Service.lmpl
{
    internal class PageModuleService : IPageModuleService
    {
        private readonly IPageModuleCollect _Service;
        private readonly IFileService _File;
        public PageModuleService ( IPageModuleCollect service,
            IFileService file )
        {
            this._File = file;
            this._Service = service;
        }

        public long Add ( PageModuleAdd data )
        {
            return this._Service.Add(data);
        }

        public PageModuleDto Get ( long id )
        {
            DBPageModule source = this._Service.Get(id);
            return source.ConvertMap<DBPageModule, PageModuleDto>();
        }

        public PageModuleBase[] Gets ( long templateId )
        {
            DBPageModule[] list = this._Service.Gets<DBPageModule>(templateId);
            if ( list.IsNull() )
            {
                return Array.Empty<PageModuleBase>();
            }
            return list.ConvertMap<DBPageModule, PageModuleBase>();
        }

        public bool Set ( long id, PageModuleSet set )
        {
            DBPageModule source = this._Service.Get(id);
            long[] dropId = source.ModuleConfig.GetDropFileId();
            if ( this._Service.Set(source, set) )
            {
                this._File.Sync(set.FileId, source.Id, dropId);
                new PageModuleEvent(source).Public("Update");
                return true;
            }
            return false;
        }
        public void Delete ( long id )
        {
            DBPageModule source = this._Service.Get(id);
            this._Service.Delete(source);
            new PageModuleEvent(source).Public("Delete");
            this._File.Drop("PageModuleImg", id);
        }

        public void SetSort ( ModuleSortSet[] sorts )
        {
            this._Service.SetSort(sorts);
        }
    }
}
